/*
 * cfg_file.h
 *
 *  Created on: Nov 1, 2013
 *      Author: killerg
 */

#ifndef CFG_FILE_H_
#define CFG_FILE_H_

#include "util.h"

#include <string>
#include <string.h>
#include <vector>

class cfg_file_t {
public:
    bool load(const char* basename, const char* prefix = NULL) {
        std::string file_path;
        if (prefix == NULL || strlen(prefix) == 0) {
            file_path = fmt_cstr("%s/cfg/%s", get_deploy(), basename);
        } else {
            file_path = fmt_cstr("%s/cfg/%s_%s", get_deploy(), prefix, basename);
        }

        const char* file = load_file(file_path.c_str());
        //printf("%s\n", file);
        data = to_json(file);
        if (data.empty() || data.isNull()) {
            UTIL_LOG(E, "cfg_file_t::load file %s empty or noexist", basename);
            return false;
        }
        name = basename;
        return true;
    }

    template<typename NUMTYPE>
    void get_nums(const char* field, const char* delim, std::vector<NUMTYPE> &nums) {
        Json::Value ret = data.get(field, Json::Value::null);
        if (ret.isNull()) {
            UTIL_LOG(E, "cfg_file_t::get_nums cfg:%s has no field:%s", name.c_str(), field);
            return;
        }

        id_list<NUMTYPE>(ret, nums);
    }

    double get_double(const char* field, double def = 0.0f) {
        Json::Value ret = data.get(field, Json::Value::null);
        if (ret.isNull()) {
            UTIL_LOG(E, "cfg_file_t::get_double cfg:%s has no field:%s", name.c_str(), field);
            return def;
        }
        return ret.asDouble();
    }

    int32_t get_int(const char* field, int32_t def = -1) {
        Json::Value ret = data.get(field, Json::Value::null);
        if (ret.isNull()) {
            UTIL_LOG(E, "cfg_file_t::get_int cfg:%s has no field:%s", name.c_str(), field);
            return def;
        }
        return ret.asInt();
    }

    bool get_bool(const char* field, bool def = false) {
        Json::Value ret = data.get(field, Json::Value::null);
        if (ret.isNull()) {
            UTIL_LOG(E, "cfg_file_t::get_bool cfg:%s has no field:%s", name.c_str(), field);
            return def;
        }
        return ret.asBool();
    }

    const std::string get_str(const char* field, const char* def = NULL) {
        Json::Value ret = data.get(field, Json::Value::null);
        if (ret.isNull()) {
            UTIL_LOG(E, "cfg_file_t::get_str cfg:%s has no field:%s", name.c_str(), field);
            return def;
        }
        return ret.asString();
    }

private:
    std::string name;
    Json::Value data;
};


#endif /* CFG_FILE_H_ */
